package com.sl.diary.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sl.diary.R;
import com.sl.diary.model.PointModel;
import com.sl.diary.network.LocationUpdate;
import com.sl.diary.network.LocationUpdate.LocationUpdateListener;
import com.sl.diary.util.DLog;
import com.sl.diary.util.Util;

// TODO: Auto-generated Javadoc
/**
 * The Class A001_SplashScreen.
 */
public class A001_SplashScreen extends BaseActivity implements LocationUpdateListener {
	
	/** The tag. */
	private static String TAG = "A001_SplashScreen";
	
	/** The txt_image. */
	private ImageView txt_image;
	
	/** The progress_loading. */
	private ProgressBar progress_loading;
	
	/** The txt_version. */
	private TextView txt_skip, txt_version;
	
	/** The location manager. */
	private LocationManager locationManager;
	
	private boolean endExecute = false;
	private Location location;
	
	/* (non-Javadoc)
	 * @see com.sl.diary.activity.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a001_splashscreen);
		
		initView();
		
		if(Util.isNetworkConnected(this)) {
			locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			startNewLocationUpdate();
		} else {
			showDialogError(String.format(getResources()
					.getString(R.string.connection_error)));
		}
	}
	
	/**
	 * Inits the view.
	 */
	private void initView() {
		txt_image 			= (ImageView) findViewById(R.id.logo);
		progress_loading 	= (ProgressBar) findViewById(R.id.progress_loading);
		txt_skip 			= (TextView) findViewById(R.id.txt_skip);
		txt_version 		= (TextView) findViewById(R.id.txt_version);
		
		final Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
		animFadeIn.setAnimationListener(new Animation.AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				if(endExecute) {
					startA002MainMapScreen(location);
				} else {
					endExecute = true;
				}
			}
		});
		
		final Animation animBounce = AnimationUtils.loadAnimation(this, R.anim.bounce);
		animBounce.setAnimationListener(new Animation.AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				txt_version.startAnimation(animFadeIn);
				txt_version.setVisibility(View.VISIBLE);
			}
		});
		
		txt_image.startAnimation(animBounce);
		
		// get version name
		PackageManager manager = this.getPackageManager();
		try {
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			txt_version.setText("Version " + info.versionName);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		DLog.e(TAG, "initView A001");
		DLog.e(TAG, "memory: " + Util.getMemory(this));
	}

	/* (non-Javadoc)
	 * @see com.sl.diary.network.LocationUpdate.LocationUpdateListener#onLocationSuccess(android.location.Location)
	 */
	@Override
	public void onLocationSuccess(Location location) {
		if(endExecute)
			startA002MainMapScreen(location);
		else {
			endExecute = true;
			this.location = location;
		}
	}

	/* (non-Javadoc)
	 * @see com.sl.diary.network.LocationUpdate.LocationUpdateListener#onLocationFail(java.lang.String)
	 */
	@Override
	public void onLocationFail(String error) {
		showDialogError(String.format(getResources()
				.getString(R.string.connection_error)));
	}
	
	//Update new
	/** The location updater. */
	LocationUpdate locationUpdater;
	
	/**
	 * Start new location update.
	 */
	private void startNewLocationUpdate() {
		if (locationUpdater != null)
			if (!locationUpdater.isStopUpdating())
				locationUpdater.stopUpdate();

		locationUpdater = null;
		locationUpdater = new LocationUpdate(this);
		locationUpdater.setLocationUpdateListener(this);
		locationUpdater.startAllUpdate();
	}

	/**
	 * Stop location update.
	 */
	private void stopLocationUpdate() {
		if (locationUpdater != null)
			if (!locationUpdater.isStopUpdating())
				locationUpdater.stopUpdate();
	}
	
	/**
	 * Start a002 main map screen.
	 *
	 * @param location the location
	 */
	private void startA002MainMapScreen(Location location){
		List<PointModel> pointDB = dbManager.getAllPoint();
		ArrayList<PointModel> pointList = Util.calculateNearestPoint(pointDB, location);
		Intent i = new Intent(this, A002_MainMapScreen.class);
		i.putExtra("latitude", location.getLatitude());
		i.putExtra("longitude", location.getLongitude());
		
		i.putParcelableArrayListExtra("point_list", pointList);
		startActivity(i);
		finish();
	}
	
	/**
	 * Show dialog error.
	 *
	 * @param message the message
	 */
	private void showDialogError(String message){
		final AlertDialog alerDlgErrorBase = new AlertDialog.Builder(this).create();
		alerDlgErrorBase.setTitle(R.string.error);
		alerDlgErrorBase.setMessage(message);

		// Set button cancel
		alerDlgErrorBase.setButton(String.format(getResources()
							.getString(R.string.lbl_ok)), 
							new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alerDlgErrorBase.dismiss();
				finish();
				return;
			}
		});
		if(this.isFinishing() == false){
			alerDlgErrorBase.show();
		}
	}
	
	/* (non-Javadoc)
	 * @see com.sl.diary.activity.BaseActivity#onPause()
	 */
	@Override
	public void onPause(){
		stopLocationUpdate();
		unbindDrawables(findViewById(R.id.a001_bg));
		System.gc();
		DLog.e(TAG, "onPause A001");
		DLog.e(TAG, "memory: " + Util.getMemory(this));
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		unbindDrawables(findViewById(R.id.a001_bg));
	    DLog.e(TAG, "onDestroy A001");
	    DLog.e(TAG, "memory: " + Util.getMemory(this));
	    System.gc();
	    super.onDestroy();
	}
	
	private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
        view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            	unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
        ((ViewGroup) view).removeAllViews();
        }
    }
}
